package com.david.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: MyLB
 * @Author: wangwei
 * @CreateDate: 2022/1/14 11:30
 */
@Component
public class MyLB implements ILoadBalancer {

    private AtomicInteger atomicInteger=new AtomicInteger(0);


    public final int getAndIncrement() {
        int current;
        int next;
//        do {

        current = this.atomicInteger.get();
        next = current >= Integer.MAX_VALUE ? 0 : current + 1;

        System.out.println("next>>" + next+":current>>"+current);
        boolean rs = this.atomicInteger.compareAndSet(current, next);
        System.out.println("compareAndSet>>" + rs);
        return next;
//        } while (true);
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index=getAndIncrement()%serviceInstances.size();
        return serviceInstances.get(index);
    }
}
